﻿using KC.Framework.SecurityHelper;
using KC.Framework.Tenant;
using KC.Service.Core.WebApiService.Business;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace KC.MVC.Core
{
    public class TenantResolver : SaasKit.Multitenancy.ITenantResolver<Tenant>
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ITenantUserApiService _tenantApiService;
        private readonly ILogger _logger;
        public TenantResolver(
            IServiceProvider serviceProvider,
            ITenantUserApiService tenantApiService, 
            ILogger<TenantResolver> logger)
        {
            _serviceProvider = serviceProvider;
            _tenantApiService = tenantApiService;
            _logger = logger;
        }

        public static IEnumerable<Tenant> TenantsForTest = new List<Tenant>(new[]
        {
            TenantConstant.DbaTenantApiAccessInfo,
            TenantConstant.TestTenantApiAccessInfo,
            TenantConstant.BuyTenantApiAccessInfo,
            TenantConstant.SaleTenantApiAccessInfo
        });

        public async Task<SaasKit.Multitenancy.TenantContext<Tenant>> ResolveAsync(Microsoft.AspNetCore.Http.HttpContext context)
        {
            SaasKit.Multitenancy.TenantContext<Tenant> tenantContext = null;
            //var tenant = TenantsForTest.FirstOrDefault(t =>
            //    t.Hostnames.Any(h => h.Contains(context.Request.Host.Value, StringComparison.OrdinalIgnoreCase)));

            Tenant tenant = null;
            var requestHost = context.Request.Host.Value;
            var exceptList = new List<string>() { "localhost:1001", "localsso.kcloudy.com", "testsso.kcloudy.com", "betasso.kcloudy.com", "sso.kcloudy.com", "localhost:1003", "localadmin.kcloudy.com", "testadmin.kcloudy.com", "betaadmin.kcloudy.com", "admin.kcloudy.com", "localhost:1004", "localadminapi.kcloudy.com", "testadminapi.kcloudy.com", "betaadminapi.kcloudy.com", "adminapi.kcloudy.com" };
            if (exceptList.Contains(requestHost))
            {
                tenant = await _tenantApiService.GetTenantByName(TenantConstant.DbaTenantName);
            }
            else
            {
                var tenantName = requestHost.Split(".")[0];
                tenant = await _tenantApiService.GetTenantByName(tenantName);
            }

            _logger.LogDebug(string.Format(Framework.Base.GlobalConfig.CurrentApplication?.AppName + "|KC.MVC.Core.TenantResolver Get tenant【{0}】 from url【{1}】", tenant?.TenantName, context.Request.Scheme + "://" +  context.Request.Host.Value + context.Request.Path));

            if (tenant != null)
            {
                tenantContext = new SaasKit.Multitenancy.TenantContext<Tenant>(tenant);
            }

            return tenantContext;
        }
    }
}
